<template>
  <div>
    <el-dialog
      v-toggle-full
      v-loading.lock="loading"
      class="base-dialog storage-order-in-edit"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="title"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <p slot="title">{{ editId ? '编辑入库单信息' : '新增入库单信息' }}</p>
      <el-form
        ref="formData"
        :model="formData"
        :rules="formDataRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="业务类型"
              prop="orderTypeCode"
              :error="errorMsg.orderTypeCode"
            >
              <el-select
                v-model="formData.orderTypeCode"
                placeholder="业务类型"
              >
                <el-option
                  v-for="item in orderTypeData"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="入库仓库"
              prop="storageId"
              :error="errorMsg.storageId"
            >
              <el-select
                v-model="formData.storageId"
                filterable
                placeholder="入库仓库"
              >
                <el-option
                  v-for="item in storageIdData"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="责任人"
              prop="personLiableId"
              :error="errorMsg.personLiableId"
            >
              <el-select
                v-model="formData.personLiableId"
                placeholder="请选择责任人"
              >
                <el-option
                  v-for="item in sysUserData"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入库危化品" prop="productNum">
              <el-select
                v-model="formData.productNum"
                filterable
                remote
                placeholder="请输入危化品名称或编号"
                :remote-method="remoteMethod"
                :loading="searchLoading"
                style="width: 83%; float: left"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
              <!-- <el-input
              v-model="formData.productNum"
              placeholder="请输入危化品名称或编号"
              autocomplete="off"
              style="width: 90%; float: left;"
              ></el-input> -->
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="getStorageProductList()"
              >
                添 加
              </el-button>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="selectProductList()"
                >选 择</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-table
          v-if="formData.productList.length > 0"
          :data="formData.productList"
          :header-cell-style="{ height: '50px' }"
          :cell-style="{ height: '70px', overflow: 'auto' }"
          style="width: 100%; height: auto; overflow: auto"
        >
          <el-table-column label="编号">
            <template slot-scope="scope">
              {{ scope.row.productNum }}
            </template> </el-table-column
          ><el-table-column label="名称">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="型号规格">
            <template slot-scope="scope">
              {{ scope.row.specifications }}
            </template>
          </el-table-column>
          <el-table-column label="分类">
            <template slot-scope="scope">
              {{ scope.row.classOneName }}
            </template>
          </el-table-column>
          <el-table-column label="形态">
            <template slot-scope="scope">
              {{ scope.row.morphologyName }}
            </template>
          </el-table-column>
          <el-table-column label="存储条件">
            <template slot-scope="scope">
              {{ scope.row.storageConditionName }}
            </template>
          </el-table-column>
          <el-table-column label="包装单位">
            <template slot-scope="scope">
              {{ scope.row.unitName }}
            </template>
          </el-table-column>
          <el-table-column label="生产商">
            <template slot-scope="scope">
              {{ scope.row.manufacturerName }}
            </template>
          </el-table-column>
          <el-table-column label="应收数量">
            <template slot-scope="scope">
              <el-form-item
                :key="scope.$index"
                :prop="'productList.' + scope.$index + '.receiveAmount'"
                label-width="0px"
                :rules="[
                  { required: true, message: '必填项', trigger: 'change' },
                  {
                    validator: Helper.validateFunctionPositiveIntegerNumber,
                    trigger: 'change',
                  },
                ]"
              >
                <el-input
                  v-model="scope.row.receiveAmount"
                  autocomplete="off"
                  type="number"
                  min="0"
                  placeholder="请输入"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <div class="base-table-operation">
                <el-link type="danger" @click="deleteProduct(scope.$index)"
                  >删除</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top: 20px">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" :error="errorMsg.remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 选择危化品 -->
      <SelectProductListDialog
        v-if="dialogProductVisible"
        ref="SelectProductListDialog"
        :dialog-product-visible.sync="dialogProductVisible"
        @confirmSelected="confirmSelected"
      >
      </SelectProductListDialog>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictList } from "../../../../api/System/SystemDict.js";
import {
  create,
  update,
  getStorageList,
  getInfo,
} from "../../../../api/Storage/StorageOrderIn.js";
import { getList } from "../../../../api/Storage/StorageProduct.js";
import SelectProductListDialog from "../../../../components/SelectProductListDialog.vue";
import {getUserListNoPage} from "@/ModulePermission/api/Permission/PermissionUser.js";

export default {
  name: "StorageOrderInEdit",
  components: { SelectProductListDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
    orderNum: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      title: "新增入库单信息",
      appId: 1000,
      loading: false,
      loading2: false,
      innerDialogFormVisible: false,
      dialogProductVisible: false,
      orderTypeData: [],
      storageIdData: [],
      sysUserData: [],
      formData: {
        id: 0,
        personLiableId: null,
        personLiableName: null,
        orderTypeCode: null,
        storageId: null,
        productNum: null,
        productList: [],
        remark: "",
      },
      formDataRules: {
        orderTypeCode: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        storageId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        personLiableId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],

        // remark: [
        //   {
        //     required: true,
        //     trigger: "blur",
        //     validator: this.Helper.validateFunction,
        //   },
        // ]
      },
      initErrorMsg: {
        orderTypeCode: "",
        storageId: "",
        personLiableId: "",
      },
      errorMsg: {
        orderTypeCode: "",
        storageId: "",
        personLiableId: "",
      },
      searchLoading: false,
      productOptions: [],
      selectionTables: [],
    };
  },
  watch: {},
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },
  methods: {
    async init() {
      // 查询字典表
      // 入库类型
      getDictList({ dictCode: "StorageOrder_Into_OrderTypeCode" }).then(
        (res) => {
          this.orderTypeData = res.data;
        }
      );
      await this.getStorageOptions();
      await this.getUserOptions();
      if (this.editId) {
        await this.getDetail();
      }
    },
    getDetail() {
      getInfo({ id: this.editId }).then((res) => {
        this.formData = res.data;
        this.formData.productList = res.data.product ? res.data.product : [];
        const orderTypeObj = {};
        orderTypeObj.value = res.data.orderTypeCode.toString();
        orderTypeObj.name = res.data.orderTypeName;
        this.$set(this.formData, "orderTypeCode", orderTypeObj);
        const storageObj = {};
        storageObj.value = res.data.storageId;
        storageObj.name = res.data.storageName;
        this.$set(this.formData, "storageId", storageObj);
        const personObj = {};
        personObj.value = res.data.personLiableId;
        personObj.name = res.data.personLiableName;
        this.$set(this.formData, "personLiableId", personObj);
      });
    },
    getStorageOptions() {
      return new Promise((resolve) => {
        getStorageList().then((res) => {
          if (res.data.dataList?.length > 0) {
            this.storageIdData = res.data.dataList.map((item) => {
              return {
                ...item,
                value: item.id,
              };
            });
          }
          resolve();
        });
      });
    },
    getUserOptions() {
      return new Promise((resolve) => {
     getUserListNoPage().then((res) => {
            if (res.data?.length > 0) {
              this.sysUserData = res.data.map((item) => {
                return {
                  value: item.id,
                  name: item.name,
                };
              });
            }
            resolve();
          });
      });
    },
    remoteMethod(query) {
      if (query !== "") {
        this.searchLoading = true;
        getList({
          nameOrNum: query,
          status: 1,
          isException: 0,
          pageIndex: 1,
          pageSize: 10,
        }).then((res) => {
          this.searchLoading = false;
          if (res.data.dataList?.length > 0) {
            this.productOptions = res.data.dataList.map((item) => {
              return {
                ...item,
                value: item.id,
                productId: item.id,
              };
            });
          }
        }).catch(() => { });
      } else {
        this.productOptions = [];
      }
    },
    getStorageProductList() {
      const productList = [];
      if (this.formData.productNum && this.formData.productNum.productId) {
        if (this.editId) {
          this.formData.productNum = {
            id: "",
            orderId: "",
            productId: this.formData.productNum.productId,
            productNum: this.formData.productNum.productNum,
            receiveAmount: "",
            name: this.formData.productNum.name,
            classOneName: this.formData.productNum.classOneName,
            manufacturerName: this.formData.productNum.manufacturerName,
            morphologyName: this.formData.productNum.morphologyName,
            specifications: this.formData.productNum.specifications,
            unitName: this.formData.productNum.unitName,
            storageConditionName: this.formData.productNum.storageConditionName,
            roughWeight: this.formData.productNum.roughWeight,
          };
        }
        productList.push(this.formData.productNum);
        this.formData.productList =
          this.formData.productList.concat(productList);
        this.formData.productList = this.unique(
          this.formData.productList,
          "productId"
        );
      }
    },
    unique(arr, u_key) {
      const map = new Map();
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item);
        }
      });
      return [...map.values()];
    },
    deleteProduct(index) {
      this.Helper.deleteConfirm(() => {
        this.formData.productList.splice(index, 1);
      });
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
      this.$refs["formData"].resetFields();
      this.$emit("update:editId", "");
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.formData.productList?.length > 0) {
            var product = this.formData.productList.map((item) => {
              return {
                productId: item.productId,
                productNum: item.productNum,
                receiveAmount: item.receiveAmount,
              };
            });
          } else {
            this.$message.error("请添加入库清单!");
            return false;
          }
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.formData.id <= 0) {
            // eslint-disable-next-line no-unused-vars
            const {
              orderTypeCode,
              storageId,
              personLiableId,
              ...formData
            } = this.formData;
            console.log(this.formData);
            console.log(personLiableId);
            create({
              ...formData,
              orderTypeCode: orderTypeCode.value,
              orderTypeName: orderTypeCode.name,
              storageId: storageId.value,
              storageName: storageId.name,
              personLiableId: personLiableId.value,
              personLiableName: personLiableId.name,
              product: product,
            }).then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            }).catch(() => {
              this.loading = false;
            });
          } else {
            // eslint-disable-next-line no-unused-vars
            const { productNum, productList, ...formData } = this.formData;
            update({
              ...formData,
              orderTypeCode: this.formData.orderTypeCode.value,
              orderTypeName: this.formData.orderTypeCode.name,
              storageId: this.formData.storageId.value,
              storageName: this.formData.storageId.name,
              personLiableId: this.formData.personLiableId.value,
              personLiableName: this.formData.personLiableId.name,
              product: product,
              orderNum: this.orderNum,
            }).then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            }).catch(() => {
              this.loading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("orderTypeCode", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("storageId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("personLiableId", this.errorMsg, res.msg);
      }
    },
    // 选择危化品
    selectProductList() {
      this.dialogProductVisible = true;
    },
    confirmSelected(data) {
      if (data && data.length > 0) {
        const mergeData = this.formData.productList.concat(data);
        this.formData.productList = this.unique(mergeData, "productId");
      }
    },
  },
};
</script>
<style lang="scss">
.storage-order-in-edit {
  .el-table .cell {
    overflow: visible;
  }
}
</style>
